package JUC;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class MySpinLock {
    // 刚开始的时候线程默认为null
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock(){
//        int times  = 0;
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+" 抢到锁了！");
        // 如果判断条件是true，说明CAS返回的值是false，代表当前已经有线程在占用，这时候就是不断自旋等线程被释放的状态
        while (!atomicReference.compareAndSet(null,thread)){
//            System.out.println(Thread.currentThread().getName()+" 正在自旋,等待线程释放");
//            times++;
//            if (times > 10){
//                System.out.println("自旋时间太长，转重量级锁了");
//                break;
//            }
        }
    }

    public void unlock(){

        atomicReference.compareAndSet(Thread.currentThread(),null);
        System.out.println(Thread.currentThread().getName()+" 解锁了");
    }
}

class Test{
    public static void main(String[] args) throws InterruptedException {
        MySpinLock mySpinLock = new MySpinLock();
        new Thread(() -> {
            mySpinLock.lock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mySpinLock.unlock();
        },"A").start();


        new Thread(() -> {
            mySpinLock.lock();
            mySpinLock.unlock();
        },"B").start();
    }
}